//测试数据，demoData.index表示index文件调用的数据，demoData.member表示member也需要调用的数据
var common = {
  
    //获取当前目录Widget格式的路径
    getWidgetPath: function() {
        var pagePath = window.location.href.replace("file://" + api.wgtRootDir, "widget://");

        var widgetPath = pagePath.substring(0, pagePath.lastIndexOf("/"));

        if (api.systemType == "android") {
            widgetPath = widgetPath + "/";
        }
        return widgetPath;
    },

    //获取当前目录的相对路径
    getRelativePath: function() {
        var pagePath = window.location.href;
        if (api.wgtRootDir.indexOf("file://") != -1) {
            pagePath = pagePath.replace(api.wgtRootDir, "");
        } else {
            pagePath = pagePath.replace("file://" + api.wgtRootDir, "");

        }
        var length = pagePath.split("/").length - 2;
        var relativePath = "";
        if (length == 0) {
            relativePath = "./";
        } else {

            for (var i = 0; i < length; i++) {
                relativePath = relativePath + "../";
            }

        }
        return relativePath;
    },

    //根据返回数据ret.ui.css 字段导入CSS文件
    importCss: function(cssModeArray) {

        var relativePath = this.getRelativePath();

        for (var i = 0; i < cssModeArray.length; i++) {
            var item = cssModeArray[i].split("_");
            var cssPath = "";
            if (item.length > 1) {
                cssPath = relativePath + "css/" + item[0] + "/" + item[1] + ".css";
            } else {
                cssPath = relativePath + "css/" + item[0] + "/" + item[0] + ".css";
            }

            $("html head").append('<link rel="stylesheet" type="text/css" href="' + cssPath + '"/>');
        }
    },
    //根据返回数据ret.ui.js 字段导入js 文件
    importJs: function(jsModeArray) {
        var relativePath = this.getRelativePath();

        for (var i = 0; i < jsModeArray.length; i++) {
            var item = jsModeArray[i].split("_");
            var jsPath = "";
            if (item.length > 1) {
                jsPath = relativePath + "script/" + item[0] + "/" + item[1] + ".js";
            } else {
                jsPath = relativePath + "script/" + item[0] + "/" + item[0] + ".js";
            }

            $("html head").append('<script type="text/javascript" src="' + jsPath + '"></script>');
        }


    },

    //插入模板代码到body后面，通过取最后一个匹配的规则覆盖原来的模板
    insertTemplate: function(template) {
        $("html body").append(template);
    },

    //替换页面HTML代码
    replacePage: function(html) {
        document.write(html);
    },

    //根据UI字段和返回数据格式化模板写入指定的HTML容器内
    applyUI: function(ui, data, templateClass, templateHtmlBox) {
        //重定向到新的URL地址
        if (ui.url != null && ui.url != "") {
            setTimeout(function() {
                window.location.href = ui.url;
            }, 200);
            return;
        }

        //重写页面内容
        if (ui.html != null && ui.html != "") {
            this.replacePage(ui.html);
            return;
        }

        //导入css模块
        this.importCss(ui.css);
        //导入js模块

        this.importJs(ui.js);

        //如果返回UI模板不为空则插入模板，用以增加或替换原有的模板
        if (ui.template != null && ui.template != "") {
            this.insertTemplate(ui.template);
        }

        //如果存在默认的main-ui模板,则初始化模板
        if ($(".main-ui").length > 0) {
            var tmphtml = $(".main-ui").last().text();
            if (tmphtml != null && tmphtml != "" && tmphtml != "undefined") {
                var htmlfn = doT.template(tmphtml);
                $("#main-box").html(htmlfn(data));
            }
        }

        //如果模板存在则格式化模板，然后写入容器
        if (templateClass && templateClass != "") {
            var tpl = $(templateClass).last().text();
            if (tpl != null && tpl != "" && tpl != "undefined") {
                var htmlfn = doT.template(tpl);
                if (templateHtmlBox && templateHtmlBox != "") {
                    $(templateHtmlBox).html(htmlfn(data));
                }
            }
        }

        //如果callback有值则运行eval(ret.ui.callback)执行回调
        if (ui.callback != null && ui.callback != '') {
            eval(ui.callback);
        }


    },

    initPageDataUI: function(requesturl, param,callback) {
        //初始化页面数据和UI
        api.ajax({
            url: requesturl,
            method: 'post',
            data: {
                values: param
            },
        }, function(ret, err) {
            //测试数据
            if (demoData) {
                if (param.pageName && demoData[param.pageName]) {
                    ret = demoData[param.pageName];
                } else {
                    ret = demoData["index"];
                }
            }

            common.applyUI(ret.ui, ret.data, param.templateClass, param.templateHtmlBox);
            if (callback) {
                callback(ret, err);
            }
        });
    },
    ajax: function(requesturl,param,timeout,callback) {
        //封装了ajax请求
        api.ajax({
            url: requesturl,
            method: 'post',
            data: {
                values: param
            },
            timeout:timeout
        }, function(ret, err) {
            if (callback) {
                callback(ret, err);
            }
        });

    },

    InitCommonTemplateData: function(layout, callback) {
        //初始化APP通用的模板存入本地供其他页面调用
        if (layout == null || layout == "undefined") {
            layout = "layout";
        }

        var templatefile = this.getWidgetPath() + "html/" + layout + "/template.html";

        //读取文本文件内容
        //var templatefile=this.getRelativePath()+"html/"+layout+"/template.html";
        api.readFile({
            path: templatefile
        }, function(ret, err) {
            if (ret) {
                $("body").append(ret.data);
                window.templates = {};
                //each() 方法规定为每个匹配元素规定运行的函数
                $(".templatesc").each(function() {
                    var tid = $(this).attr("id");
                    if (tid != undefined) {
                        window.templates[tid] = $(this).html();
                    }
                });

                $api.setStorage("templates", window.templates);
                callback();

            } else {

            }
        });
        return;
    },
    getCommonTemplateHtml: function(templateName) {
        //获取指定模板名称的模板内容
        var templates = $api.getStorage("templates");
        if (templates != null && templates != "undefined") {
            return templates[templateName];
        } else {
            return "";
        }

    },

    bindUIData: function(template, data, elem) {
        //根据模板和数据格式化模板写入 html容器
        if (template != null && template != "" && template != "undefined") {
            var htmlfn = doT.template(template);
            $(elem).html(htmlfn(data));
        }
    },

    openFrame: function(pageurl, param) {
        //打开一个frame窗口,判断是否有传窗口名称，没有则通过文件路径获取名称传入
        if (param == null) {
            param = {};
        }

        if (param.name == null) {
            var arr = pageurl.split("/");
            param.name = arr[arr.length - 1].replace(".html", "");
            if (arr.length > 1) {
                param.name = arr[arr.length - 2].replace(".", "") + param.name;
            }
        }

        api.openFrame({
            name: param.name,
            url: pageurl,
            rect: {
                x: 0,
                y: 60,
                w: api.winWidth,
                h: api.winHeight - 100
            },
            pageParam: param
        });
    },

    //网络交换的提示
    getApiShowProgress: function() {
        api.showProgress({
            style: 'default',
            animationType: 'fade',
            title: '努力加载中...',
            text: '请稍等...',
            modal: false
        });

    },
    //关闭 网络交换的提示
    getApiHideProgress: function() {
        api.hideProgress();
    },
    //得到后台需要的请求参数
    getJSONParame: function(keyword, json) {
        var time = Date.parse(new Date());
        var token = $api.getStorage(NewFiData.appParameKey.userToken);
        var userid = $api.getStorage(NewFiData.appParameKey.userId);
        if (token == undefined) {
            token = 'null';
        }
        if (userid == undefined) {
            userid = '0';
        }
        var appType = 1;
        if(api.appVersion == '牛郎WiFi'){
                appType = 2;
        }
        var stringJson = "keyword=" + keyword + "&params=" + json + "&time=" + time + "&token=" + token + "&userid=" + userid + "&key=niulang2016";
        var md5sign = hex_md5(stringJson);
        var params = {
            params: json,
            token: token,
            userid: userid,
            time: time,
            keyword: keyword,
            sign: md5sign,
            apMac: $api.getStorage(NewFiData.wifiKey.apMac),
            apName: $api.getStorage(NewFiData.wifiKey.wifiName),
            NF_callid: common.getRandom20(),
            appType: appType
        }
        return params;
    },
    //生成一个20位的随机数
    getRandom20: function() {
        var data = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"];
            var result = "";
            for (var i = 0; i < 20; i++) {
                r = Math.floor(Math.random() * 10);
                result += data[r];
            }
            return result;
    },


    /**显示或提示一些请求网络时发生的错误信息
    *code 错误状态码 msg 提示的信息
    *code 11:没有找到代理 21:500/404一般是服务器异常
    *0/1 服务器访问通过了 一些验证没有过   10 客户端定义的提示信息
    */
    getShowViewError:function(code,msg){
      switch (code) {
        case 11:
          alert(msg);
          break;
        case 21:case 500:case 404:
            if(msg == undefined){
              msg = '服务器异常'
            }
            getToast(msg,3000);
            break;
        case 0 :case -1:
               if(msg == '' || msg == undefined){
                 msg = '服务器异常';
               }
              getToast(msg,2000);
            break;
        case 10:
            getToast(msg,2000);
            break;
        case -2:
          break;
        default:
            getToast('code:'+code,2000);
      }
    },
    //打印日志 和写日志文件
    getConsole:function(sign,msg){
      console.log('..sign..'+sign+'...msg...'+msg+'..time..'+new Date().toLocaleString());
    }

};
 //吐司
 function getToast(msg,duration){
   api.toast({
       msg: msg,
       duration: duration,
       location: 'bottom'
   });
 }
